<template>
    <div class="wrap">
        <div style="margin-bottom: 10%">
            <el-steps :active="active" finish-status="success" align-center>
                <el-step title="企业信息"/>
                <el-step title="联系人"/>
                <el-step title="营业执照"/>
            </el-steps>
            <el-form ref="form" :model="data" :rules="mRules" label-width="110px" size="mini">
                <!-- 企业信息 -->
                <div v-if="active === 0">
                    <el-form-item label="企业名称" prop="name">
                        <el-input readonly v-model="data.name"/>
                    </el-form-item>
                    <el-form-item label="所属行业" prop="industryId">
                        <el-input readonly v-model="industryText" @click.native="showDrawer"/>
                    </el-form-item>
                    <el-form-item label="企业规模" prop="companyScale">
                        <el-radio-group v-model="data.companyScale" size="medium">
                            <el-radio v-for="companyScale in companyScaleList" :label="companyScale"
                                      :key="companyScale">
                                {{companyScale}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="企业类型" prop="unitType">
                        <el-checkbox-group v-model="data.unitType">
                            <el-checkbox v-for="unitType in unitTypeList" :label="unitType" :key="unitType">
                                {{unitType}}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="企业简介" prop="companyContent">
                        <!--                        <Tinymce style="width: 80%;" v-if="tinymceActive" v-model="data.companyContent"-->
                        <!--                                 :height="521"/>-->
                        <el-input type="textarea"
                                  :autosize="{ minRows: 5, maxRows: 10}"
                                  v-model="data.companyContent"/>
                    </el-form-item>
                    <el-form-item label="企业简介图片" prop="companyImages">
                        <UploadImage :upload="contentImgUpload" @uploadBack="contentImgUpload.uploadBack"/>
                    </el-form-item>
                    <el-form-item label="企业地址" required="true">
                        <el-input readonly v-model="selectCity" @click.native="showCityDrawer" placeholder="请选择省市区"/>
                    </el-form-item>
                    <el-form-item label="详细地址" prop="address">
                        <el-input v-model="data.address" placeholder="请填写详细地址"/>
                    </el-form-item>
                </div>
                <!-- 联系人 -->
                <div v-if="active === 1">
                    <el-form-item label="固定电话" prop="telephone">
                        <el-input v-model="data.telephone" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="联系人1" prop="contactPeople1">
                        <el-input v-model="data.contactPeople1" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="联系人1职务" prop="contactPeople1Job">
                        <el-input v-model="data.contactPeople1Job" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="联系人1手机" prop="phone">
                        <el-input v-model="data.phone" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="联系人2" prop="contactPeople2">
                        <el-input v-model="data.contactPeople2" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="联系人2职务" prop="contactPeople2Job">
                        <el-input v-model="data.contactPeople2Job" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="联系人2手机" prop="phone2">
                        <el-input v-model="data.phone2" placeholder="暂无数据"/>
                    </el-form-item>
                </div>
                <!-- 营业执照 -->
                <div v-if="active === 2">
                    <div>
                        <el-form-item prop="businessLicense">
                            <UploadImage :upload="businessLicenseImgUpload"
                                         @uploadBack="businessLicenseImgUpload.uploadBack"/>
                        </el-form-item>
                    </div>
                </div>
                <el-drawer
                        :visible.sync="drawerShow"
                        :withHeader="false"
                        :direction="'btt'"
                        :size="'310px'">
                    <el-tabs v-model="industryActive" @tab-click="handleClick" :type="'card'" style="margin: 5px">
                        <el-tab-pane label="一级分类" name="first">
                            <mt-picker :slots="firstSlots" :valueKey="'name'"
                                       @change="onFirstIndustryChange"/>
                        </el-tab-pane>
                        <el-tab-pane label="二级分类" name="second">
                            <mt-picker :slots="secondSlots" :valueKey="'name'"
                                       @change="onSecondIndustryChange"/>
                        </el-tab-pane>
                    </el-tabs>
                    <div style="text-align: right;padding: 0 20px;">
                        <el-button type="primary" round @click="drawerClick">{{industryActive == 'first'?'下一步':'确定'}}
                        </el-button>
                    </div>
                </el-drawer>
                <el-drawer :visible.sync="cityDrawerShow"
                           :withHeader="false"
                           :direction="'btt'"
                           :size="'230px'">
                    <citySelectPhone @getLinkage="confirmCityDrawer" @closeLinkage = "closeCityDrawer"/>
                </el-drawer>
            </el-form>
        </div>
        <div class="toolbar-bottom-right">
            <el-button v-if="active !== 0" type="primary" @click="lastStep">上一步</el-button>
            <el-button v-if="active !== 2" type="primary" @click="next">下一步</el-button>
            <el-button v-else type="primary" @click="insert">保存</el-button>
            <el-button @click="back('WxIndex')">取消</el-button>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Emit} from 'vue-property-decorator'
    import {API} from "@/core/api/API";
    import {mixins} from "vue-class-component";
    import BaseVue from "@/core/mixin/BaseVue";
    import $http from "@/core/utils/http";
    import Kit from "@/core/mixin/Kit";
    import {getStorage, getUserInfo} from "@/core/utils/storage";
    import UploadImage from "@/components/Updalod/UploadImage.vue";
    import {Toast} from 'mint-ui';
    import {copy, tree} from "@/core/utils/Utils";
    import Tinymce from "@/components/Tinymce/Tinymce.vue";
    import {validate} from "@/core/utils/validate";
    import {rule} from "@/core/utils/rule";
    import citySelectPhone from "@/components/citySelect/citySelectPhone.vue";

    //按需引用
    @Component({
        name: 'CompanyInfoWx',
        components: {Tinymce, UploadImage, citySelectPhone},
    })
    export default class CompanyInfoWx extends mixins(BaseVue, Kit) {
        tinymceActive: boolean = false;
        // 文件上传组件配置对象
        contentImgUpload = {
            fileList: [],
            url: "/company/companyInfo/uploadFile",
            listType: "text",
            platform: "phone",
            maxSize: "10",
            uploadBack: this.contentImgUploadCallBack,
        };
        businessLicenseImgUpload = {
            fileList: [],
            url: "/company/companyInfo/uploadFile",
            listType: "text",
            platform: "phone",
            maxSize: "10",
            uploadBack: this.businessLicenseUploadCallBack,
        };

        mRules = {
            name: [rule.notNullChange()],
            industryId: [rule.notNullChange()],
            companyScale: [rule.notNullChange()],
            unitType: [rule.notNullChange()],
            companyContent: [rule.notNullChange()],
            address: [rule.notNullBlur()],
            telephone: [rule.notNullChange()],
            contactPeople1: [rule.notNullChange()],
            contactPeople1Job: [rule.notNullChange()],
            phone: [rule.notNullChange()],
            companyImages: [rule.notNullChange()],
            businessLicense: [rule.notNullChange()],
        };
        // 表单数据
        data: any = {
            unitType: []
        };

        // 选中的省市区
        selectCity: string = "";
        // 行业字典
        industryList: any = [];
        // 当前选中行业
        industryText: string = "暂无数据";
        activityFirstIndustry: any = {};
        activitySecondIndustry: any = {};
        industryActive: string = "first";
        firstSlots: any = [{
            values: [],
            textAlign: 'center'
        }];
        secondSlots: any = [{
            values: [],
            textAlign: 'center'
        }];
        // 企业类型字典
        unitTypeList: any = [];
        // 企业规模字典
        companyScaleList: any = [];
        //关闭时是否刷新分页
        backRefresh: boolean = false;

        // 当前活跃步骤下标
        active: number = 0;

        // 行业选择抽屉是否显示
        drawerShow: boolean = false;
        // 城市选择抽屉是否显示
        cityDrawerShow: boolean = false;

        // 上一步按钮
        lastStep() {
            this.active--;
        }

        // 下一步按钮
        next() {
            // 校验企业信息
            if (this.active == 0) {
                if (!this.data.name) {
                    Toast({message: '企业名称不能为空！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.name.length > 50) {
                    Toast({message: '企业名称不能超50个字符！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.industryId) {
                    Toast({message: '请选择所属行业！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.companyScale) {
                    Toast({message: '请选择企业规模！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.unitType || this.data.unitType.length == 0) {
                    Toast({message: '请选择企业类型！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.companyContent) {
                    Toast({message: '请填写企业简介！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.companyContent) {
                    Toast({message: '请填写企业简介！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.companyImages || this.data.companyImages.length == 0) {
                    Toast({message: '请上传企业简介图片！', position: 'bottom', duration: 3000});
                    return;
                }
                if(!this.selectCity){
                    Toast({message: '请选择企业所在省市区！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.address) {
                    Toast({message: '请填写详细地址！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.address.length > 512) {
                    Toast({message: '详细地址不能超过512个字符！', position: 'bottom', duration: 3000});
                    return;
                }
            }
            // 校验联系人信息
            else if (this.active == 1) {
                if (!this.data.telephone) {
                    Toast({message: '请填写固定电话！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!validate.isTelephone(this.data.telephone)) {
                    Toast({message: '请填写正确的固定电话！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.contactPeople1) {
                    Toast({message: '请填写联系人1姓名！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.contactPeople1.length > 20) {
                    Toast({message: '联系人1姓名不能超过20个字符！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!this.data.contactPeople1Job) {
                    Toast({message: '请填写联系人1职位！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.contactPeople1Job.length > 20) {
                    Toast({message: '联系人1职位不能超过20个字符！', position: 'bottom', duration: 3000});
                    return;
                }
                if (!validate.isPhone(this.data.phone)) {
                    Toast({message: '请填写正确的联系人1电话！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.contactPeople2 && this.data.contactPeople2.length > 20) {
                    Toast({message: '联系人2姓名不能超过20个字符！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.contactPeople2Job && this.data.contactPeople2Job.length > 20) {
                    Toast({message: '联系人2职位不能超过20个字符！', position: 'bottom', duration: 3000});
                    return;
                }
                if (this.data.phone2 && !validate.isPhone(this.data.phone2)) {
                    Toast({message: '请填写正确的联系人2电话！', position: 'bottom', duration: 3000});
                    return;
                }
            }
            this.active++;
            if (this.active > 2) this.active = 0;
        }

        activated() {
            this.tinymceActive = true;
        }

        deactivated() {
            this.tinymceActive = false
        }

        //初始化
        async mounted() {
            // 企业类型字典数据
            this.unitTypeList = getStorage("companyType");
            // 企业规模字典数据
            this.companyScaleList = getStorage("companyScale");
            await this.getIndustryTypeList();
            await this.getCompanyInfo();
            this.tinymceActive = true;
        }

        // 获取行业类型数据
        async getIndustryTypeList() {
            return $http.post(API.industryTypeList, {}).then((res: any) => {
                if (res.success) {
                    this.industryList = tree(res.data);
                    this.firstSlots[0].values = this.industryList;
                } else {
                    Toast({
                        message: '行业类型数据获取失败',
                        position: 'bottom',
                        duration: 3000
                    });
                }
            });
        }

        // 获取企业信息
        async getCompanyInfo() {
            return $http.post(API.companyInfoByUserId, {id: getUserInfo().id}).then((res1: any) => {
                if (res1.success) {
                    this.backRefresh = true;
                    this.data = res1.data;
                    if (this.data.companyImages) {
                        this.data.companyImages = JSON.parse(this.data.companyImages);
                        this.contentImgUpload.fileList = copy(this.data.companyImages);
                    }
                    if (this.data.businessLicense) {
                        this.data.businessLicense = JSON.parse(this.data.businessLicense);
                        this.businessLicenseImgUpload.fileList = copy(this.data.businessLicense);
                    }
                    if (this.data.industryId) {
                        for (let i in this.industryList) {
                            if (this.data.industryId == this.industryList[i].id) {
                                this.industryText = this.industryList[i].name;
                                break;
                            }
                            for (let j in this.industryList[i].children) {
                                if (this.data.industryId == this.industryList[i].children[j].id) {
                                    this.industryText = this.industryList[i].children[j].name;
                                    break;
                                }
                            }
                        }
                    }
                    if (this.data.unitType) {
                        this.data.unitType = this.data.unitType.split(",");
                    } else {
                        this.data.unitType = [];
                    }
                    // 处理企业地址数据
                    if(this.data.address){
                        let addressList = this.data.address.split("-");
                        // 截取出详细地址
                        this.data.address = addressList.pop();
                        // 剩余为省市区选择数据
                        this.selectCity = addressList.join("-");
                    }
                } else {
                    Toast({
                        message: '数据丢失',
                        position: 'bottom',
                        duration: 3000
                    });
                }
            })
        }

        // 保存数据
        insert() {
            if (!this.data.businessLicense || this.data.businessLicense.length == 0) {
                this.active = 2;
                Toast({message: '请上传营业执照图片！', position: 'bottom', duration: 3000});
                return;
            }
            let data = copy(this.data);
            data.unitType = data.unitType.join(",");
            if (typeof data.industryId == 'object') {
                data.industryId = data.industryId[data.industryId.length - 1];
            }
            if (!data.id) {
                data.userId = getUserInfo().id;
                data.userAccount = getUserInfo().account;
            }
            if (data.companyImages && data.companyImages.length > 0) {
                data.companyImages = JSON.stringify(data.companyImages);
            } else {
                data.companyImages = "[]";
            }
            if (data.businessLicense && data.businessLicense.length > 0) {
                data.businessLicense = JSON.stringify(data.businessLicense);
            } else {
                data.businessLicense = "[]";
            }
            data.address = this.selectCity + "-" + data.address;
            $http.post(API.companyInfoUpdate, data).then((res: any) => {
                if (res.success) {
                    this.backRefresh = true;
                    Toast({
                        message: '操作成功',
                        position: 'bottom',
                        duration: 3000
                    });
                } else {
                    Toast({
                        message: '操作失败',
                        position: 'bottom',
                        duration: 3000
                    });
                }
            });

        }

        // 打开行业选择抽屉
        showDrawer() {
            this.drawerShow = true;
        }

        // 行业选择抽屉Tab点击事件
        handleClick() {

        }

        // 一级行业变更回调
        onFirstIndustryChange(picker: any, values: any) {
            if (values[0]) {
                this.secondSlots[0].values = values[0].children;
                this.activityFirstIndustry = values[0];
            }
        }

        // 二级行业变更回调
        onSecondIndustryChange(picker: any, values: any) {
            if (values[0]) {
                this.activitySecondIndustry = values[0];
            }
        }

        // 选择行业按钮点击事件
        drawerClick() {
            if (this.industryActive == 'first') {
                if (this.secondSlots[0].values && this.secondSlots[0].values.length > 0) {
                    this.industryActive = 'second';
                } else {
                    // 选择完成
                    this.industryText = this.activityFirstIndustry.name;
                    this.data.industryId = this.activityFirstIndustry.id;
                    this.drawerShow = false;
                }
            } else {
                // 选择完成
                this.industryText = this.activitySecondIndustry.name;
                this.data.industryId = this.activitySecondIndustry.id;
                this.drawerShow = false;
            }
        }

        // 打开省市区选择
        showCityDrawer(){
            this.cityDrawerShow = true;
        }

        // 省市区确定按钮
        confirmCityDrawer(msg:any){
            //console.log(msg)
            this.selectCity = msg.join("-");
            this.cityDrawerShow = false;
        }

        // 关闭省市区选择
        closeCityDrawer(){
            this.cityDrawerShow = false;
        }

        contentImgUploadCallBack(val: any) {
            this.data.companyImages = val.fileList;
        }

        businessLicenseUploadCallBack(val: any) {
            this.data.businessLicense = val.fileList;
        }

        //关闭事件
        @Emit("close")
        close() {
            return {refresh: this.backRefresh};
        }

    }
</script>

<style scoped lang="scss">
    .wrap {
        padding-top: 20px;
    }

    .el-form {
        margin-top: 15px;
        padding: 15px;
        border-top: 10px solid #f1f1f1;
    }

    .el-select {
        width: 100%;
    }

    .el-radio {
        width: 50%;
        margin-right: 0;
        margin-top: 5px;
    }

</style>
